import { Lose } from '../tips/lose'
import { Win } from '../tips/win'
import { Pause } from '../tips/pause'
import { Downgrade } from '../tips/downGrade'
import { Cancel } from '../tips/cancel'
import { Remove } from '../tips/remove'
import { Checkpoint_one } from '../checkpoints/checkpoint_one'
import { DashBoard } from '../dashboard/DashBoard'
import { Bubble } from '../component/bubble'
import { ReverseBubble } from '../component/reverseBubble'
import { settings } from './checkpoint_one'
import { playBackgroundMusic, pauseBackgroundMusic, playWoodHitMusic, playMetalHitMusic } from '../component/music';
import { CanvasButton } from '../component/custombutton'
import {
  env
} from '../../.eslintrc';
export class Checkpoint {
    //初始化所有变量
    constructor(canvas) {
        this.canvas = canvas;
        this.context = this.canvas.getContext('2d');
        this.width = this.canvas.width;
        this.height = this.canvas.height;

        this.bubble = new Bubble(this.context);
        this.reverseBubble = new ReverseBubble(this.context);
        this.maxBubbleSize = 100;

        this.onlyone = true;
        this.gameOver = false;
        this.countNum = 0;
        this.isUpdating = true;
        this.isPausing = false;
        this.isBackhome = false;
        this.use_prop1 = false;
        this.use_prop2 = false;
        this.use_prop3 = false;
        this.acquire_prop1 = false;         //获得道具标识
        this.acquire_prop2 = false;
        this.acquire_prop3 = false;
        this.prop1_count = 0;
        this.prop2_count = 0;
        this.prop3_count = 0;
        this.score = 0;
        this.energy = 0;
        this.blockNum = 200 + 2;         // 用于修改方块数量，前者为方块，后者为固定值地板
        this.countdownTime = 0;          //计时器
        this.bubbleTime = 4;             //小猪气泡显示时间
        this.bubble1Time = 4;            //大树气泡显示时间
        this.difficulty = 20;               //玩家与木块的高度差
        this.timeString = '';

        this.button = [];

        this.percentage = 12 / 100;               //icon百分比
        this.iconSize = Math.floor(this.width * this.percentage);        //icon高度

        this.size_1 = this.width * this.percentage / 2; // 用于调整页面字号大小 （目前仅包含时间）

        //屏幕能看到的范围
        this.visibleRect = {
            top: 0,
            bottom: this.height,
            left: 0,
            right: this.width,
        }

        // 玩家和方块的属性
        this.player = {
          x: this.width * this.percentage,
          y: this.height * (1 - this.percentage * 2),
          width: this.iconSize,
          height: this.iconSize,
          speedY: 5, // 控制移动速度，调整难度
          isMovingRight: false
      };

        this.blocks = [];
        //道具1属性
        this.prop1 = {
            x: this.width / 2 - (this.iconSize / 2 * 5),
            y: this.height - this.iconSize * 2,
            width: this.iconSize,
            height: this.iconSize
        }
        //道具2属性
        this.prop2 = {
            x: this.width / 2 - this.iconSize / 2,
            y: this.height - this.iconSize * 2,
            width: this.iconSize,
            height: this.iconSize
        }
        //道具3属性
        this.prop3 = {
            x: this.width / 2 + (this.iconSize / 2 * 3),
            y: this.height - this.iconSize * 2,
            width: this.iconSize,
            height: this.iconSize
        }

        // 定义定时器
        this.timer = null;   //暂停资源方式卡死
        this.timer = setInterval(() => {
            // 变量每秒减1
            this.bubbleTime++;
            this.bubble1Time++;
            this.countdownTime++;
        }, 1000); // 每1000毫秒（即1秒）执行一次


        wx.showLoading({
            title: '加载中......'
        });
        this.onloadImage(() => {

            for (let i = 0; i < this.blockNum; i++) {
                var status = 'wood';
                var random = Math.floor(Math.random() * 9);
                var cube = this.wood;
                if (i >= this.blockNum - 2) {
                    status = 'floor';
                }
                this.blocks.push({
                    x: this.width - this.iconSize * 2,
                    y: this.height - (this.blockNum - i) * (this.iconSize + this.difficulty),
                    width: (this.iconSize + this.difficulty) * 6 / 5,
                    height: this.iconSize + this.difficulty,
                    speedX: 0,
                    speedY: 0,
                    hasCollided: false,
                    angle: 0,
                    angleOffset: 0,
                    status: status,
                    cube: cube,
                    random: random
                });
            }
            this.init();
            wx.hideLoading();
        });
    }

    //初始化所有图片相关内容，创建等
    onloadImage(callback) {
        let loadedCount = 0;
        const totalImages = 10;

        this.wood = wx.createImage();
        this.wood.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/wood.png';
        this.wood.onload = () => {
            loadedCount++;
            checkIfAllLoaded();
        };

        this.iron = wx.createImage();
        this.iron.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/iron.png';
        this.iron.onload = () => {
            loadedCount++;
            checkIfAllLoaded();
        };

        this.gold = wx.createImage();
        this.gold.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/gold.png';
        this.gold.onload = () => {
            loadedCount++;
            checkIfAllLoaded();
        };

        this.background = wx.createImage();
        this.background.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/background/background_1.png';
        this.background.onload = () => {
            loadedCount++;
            checkIfAllLoaded();
        };

        this.pig = wx.createImage();
        this.currentSkinImage = wx.getStorageSync('currentSkinImage');
        this.pig.src = `${this.currentSkinImage}`;
        this.pig.onload = () => { 
            loadedCount++;
            checkIfAllLoaded();
        };

        //暂停属性
        this.pause_icon = wx.createImage();
        this.pause_icon.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/pause.png'
        this.pause_icon.onload = () => {
            loadedCount++;
            checkIfAllLoaded();
        };

        this.prop1_icon = wx.createImage();
        this.prop1_icon.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/prop1.png'
        this.prop1_icon.onload = () => {
            loadedCount++;
            checkIfAllLoaded();
        };

        this.prop2_icon = wx.createImage();
        this.prop2_icon.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/prop2.png'
        this.prop2_icon.onload = () => {
            loadedCount++;
            checkIfAllLoaded();
        };

        this.prop3_icon = wx.createImage();
        this.prop3_icon.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/prop3.png'
        this.prop3_icon.onload = () => {
            loadedCount++;
            checkIfAllLoaded();
        };

        this.time_icon = wx.createImage();
        this.time_icon.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/time.png'
        this.time_icon.onload = () => {
            loadedCount++;
            checkIfAllLoaded();
        };

        const checkIfAllLoaded = () => {
            if (loadedCount === totalImages && callback) {
                callback();
            }
        };
    }

    init() {
        pauseBackgroundMusic();
        if (settings.MUSIC_OPEN === true) {
            playBackgroundMusic()
        }
        this.drawButton();
        this.onloadPage();
        this.drawAnimate(); // 开始游戏主循环
    }

    drawButton() {
      let _this = this;
      let pause ={
        type: "image",
        image: "https://gitee.com/z-l-ya/game-image/raw/master/images/icons/pause.png",
        style: {
            backgroundColor: 'transparent',
            left: this.iconSize / 2,
            top: this.iconSize / 2,
            width: this.iconSize,
            height: this.iconSize
        },
        success(button) {
          _this.button.push(button);
          button.drawButton(_this.context); // 绘制按钮
          button.onTap((res) => {
              _this.buttonHide();
              _this.isPausing = true;
          })
      },
      }
      new CanvasButton(pause);
      let prop1 = {
        type: "image",
        image: "https://gitee.com/z-l-ya/game-image/raw/master/images/icons/prop1.png",
        style: {
            backgroundColor: 'transparent',
            left: this.prop1.x,
            top: this.prop1.y,
            width: this.prop1.width,
            height: this.prop1.height
        },
        success(button) {
          _this.button.push(button);
          button.drawButton(_this.context); // 绘制按钮
          button.onTap((res) => {
            // _this.buttonHide();
            // button.hideButton();
            if (_this.prop1_count === 0) {
              _this.use_prop1 = true;
            } else if (_this.prop1_count === 1) {
              for (let index = 199; index >= 0; index--) {
                  const blockTop = _this.blocks[index].y;
                  const blockBottom = _this.blocks[index].y + _this.blocks[index].height;
                  const blockLeft = _this.blocks[index].x;
                  const blockRight = _this.blocks[index].x + _this.blocks[index].width;
                  // 只有当矩形部分或全部可见时才进行绘制
                  if (blockBottom >= _this.visibleRect.top && blockTop <= _this.visibleRect.bottom &&
                      blockRight >= _this.visibleRect.left && blockLeft <= _this.visibleRect.right) {
                      // 在可见范围内，进行绘制操作
                      if (_this.blocks[index].status == 'iron') {
                          _this.blocks[index].status = 'wood';
                          _this.blocks[index].cube = _this.wood;
                          _this.use_prop1 = false;;
                          _this.prop1_count = 999;
                          break;
                      } else if (_this.blocks[index].status == 'gold') {
                          _this.blocks[index].status = 'iron';
                          _this.blocks[index].cube = _this.iron;
                          _this.use_prop1 = false;
                          _this.prop1_count = 999;
                          break;
                      }
                  }
              }
          }
          })
      },
      }
      new CanvasButton(prop1);

      let prop2 = {
        type: "image",
        image: "https://gitee.com/z-l-ya/game-image/raw/master/images/icons/prop2.png",
        style: {
            backgroundColor: 'transparent',
            left: this.prop2.x,
            top: this.prop2.y,
            width: this.prop2.width,
            height: this.prop2.height
        },
        success(button) {
          _this.button.push(button);
          button.drawButton(_this.context); // 绘制按钮
          button.onTap((res) => {
            // button.hideButton()
            if (_this.prop2_count === 0) {
              _this.use_prop2 = true;
          } else if (_this.prop2_count === 1) {
              for (let index = 199; index >= 0; index--) {
                  const blockTop = _this.blocks[index].y;
                  const blockBottom = _this.blocks[index].y + _this.blocks[index].height;
                  const blockLeft = _this.blocks[index].x;
                  const blockRight = _this.blocks[index].x + _this.blocks[index].width;
                  // 只有当矩形部分或全部可见时才进行绘制
                  if (blockBottom >= _this.visibleRect.top && blockTop <= _this.visibleRect.bottom &&
                      blockRight >= _this.visibleRect.left && blockLeft <= _this.visibleRect.right) {
                      // 在可见范围内，进行绘制操作
                      if (_this.blocks[index].angle != 0) {
                          _this.blocks[index].angle = 0;
                          _this.use_prop2 = false;;
                          _this.prop2_count = 999;
                      }
                  }
              }
              //道具2代码逻辑
          }
          })
      },
      }
      new CanvasButton(prop2);

      let prop3 = {
        type: "image",
        image: "https://gitee.com/z-l-ya/game-image/raw/master/images/icons/prop3.png",
        style: {
            backgroundColor: 'transparent',
            left: this.prop3.x,
            top: this.prop3.y,
            width: this.prop3.width,
            height: this.prop3.height
        },
        success(button) {
          _this.button.push(button);
          button.drawButton(_this.context); // 绘制按钮
          button.onTap((res) => {
            //button.hideButton();
            if (_this.prop3_count === 0) {
              _this.use_prop3 = true;
          } else if (_this.prop3_count === 1) {
              _this.prop3_count = 999;
              //道具3代码逻辑
              for (let index = _this.blocks.length - 3; index >= 0; index--) {
                  const blockTop = _this.blocks[index].y;
                  const blockBottom = _this.blocks[index].y + _this.blocks[index].height;
                  const blockLeft = _this.blocks[index].x;
                  const blockRight = _this.blocks[index].x + _this.blocks[index].width;
                  // 只有当矩形部分或全部可见时才进行绘制
                  if (blockBottom >= _this.visibleRect.bottom - _this.blocks[200].height * 6 && blockTop <= _this.visibleRect.bottom - _this.blocks[200].height * 2 &&
                      blockRight >= _this.visibleRect.left && blockLeft <= _this.visibleRect.right) {
                      // 在可见范围内，进行绘制操作
                      _this.blocks[index].angle = 0;
                      _this.blocks[index].speedX += 10;
                      _this.use_prop3 = false;
                  }
              }
              _this.score += 5;
              console.log(_this.score);
          }
          })
      },
      }
      new CanvasButton(prop3);
    }

    onloadPage() {
        // 先移除之前可能存在的触摸事件监听器
        wx.offTouchStart();
        // 监听点击事件
        wx.onTouchStart((e) => {
            const touchX = e.touches[0].clientX;
            const touchY = e.touches[0].clientY;

            // 检查是否点击了暂停按钮的范围内
            if(!(touchX >= this.iconSize / 2 && touchX <= this.iconSize * 3 / 2 && touchY >= this.iconSize / 2 && touchY <= this.iconSize * 3 / 2) && !(touchX >= this.prop1.x && touchX <= this.prop1.x + this.prop1.width && touchY >= this.prop1.y && touchY <= this.prop1.y + this.prop1.height) && !(touchX >= this.prop2.x && touchX <= this.prop2.x + this.prop2.width && touchY >= this.prop2.y && touchY <= this.prop2.y + this.prop2.height) && !(touchX >= this.prop3.x && touchX <= this.prop3.x + this.prop3.width && touchY >= this.prop3.y && touchY <= this.prop3.y + this.prop3.height)){
              // console.log("pandaun");
              this.player.isMovingRight = true;
            }
        });
    }

    drawBlock(block) {
        this.context.save();
        this.context.translate(block.x + block.width / 2, block.y + block.height / 2);
        this.context.rotate(block.angle);
        this.context.translate(-block.width / 2, -block.height / 2);
        this.context.drawImage(block.cube, 0, 0, block.width, block.height);
        this.context.restore();
    }

    //绘制帧动画
    drawAnimate() {
        if (this.isUpdating === false && this.gameOver === true) {
            this.funshowLosePopup(); // 显示失败弹窗
            return;
        }
        if (this.isPausing === true) {
            this.funshowPausePopup();
            return;
        }
        if (this.use_prop1 === true) {
            this.funshowProp1Popup();
            return;
        }
        if (this.use_prop2 === true) {
            this.funshowProp2Popup();
            return;
        }
        if (this.use_prop3 === true) {
            this.funshowProp3Popup();
            return;
        }
        if (this.score >= 5) {
          this.score = -1;
            // if (this.score > 1) { // 调试使用
            const hours = Math.floor(this.countdownTime / 3600);
            const minutes = Math.floor((this.countdownTime % 3600) / 60);
            const seconds = Math.floor(this.countdownTime % 60);

            // 确保每个时间单位都是两位数格式
            const hh = String(hours).padStart(2, '0');
            const mm = String(minutes).padStart(2, '0');
            const ss = String(seconds).padStart(2, '0');

            this.timeString = hh + ':' + mm + ':' + ss;
            wx.cloud.init({
              env: 'prod-8gf88ck5bb3ddd38'
            }) 
            wx.cloud.callContainer({
              "config": {
                "env": "prod-8gf88ck5bb3ddd38"
              },
              "path": "/apis/ranks/createRankInfo",
              "header": {
                'content-type': 'application/json',
                'AuthToken': wx.getStorageSync("AuthToken"),
                "X-WX-SERVICE": env.service
              },
              "data": {
                'completeTime':this.timeString,
              },
              "method": "POST",
              success: (res) => {
                console.log(res);
            },
            fail: console.warn,
            })

            // this.funshowWinPopup(); // 传参通关时间
            // return;
        }

        if(this.score === -1) {
          for(let index=this.blocks.length-3; index>=0; index--){
            const blockTop = this.blocks[index].y;
            const blockBottom = this.blocks[index].y + this.blocks[index].height;
            const blockLeft = this.blocks[index].x;
            const blockRight = this.blocks[index].x + this.blocks[index].width;
            // 只有当矩形部分或全部可见时才进行绘制
            if (blockBottom >= this.visibleRect.bottom-this.blocks[3].height*3 && blockTop <= this.visibleRect.bottom-this.blocks[3].height*2&&
                blockRight >= this.visibleRect.left && blockLeft <= this.visibleRect.right) {
                    if(this.blocks[index].x > Math.floor(this.width / 100 * 95)){
                    this.funshowWinPopup();
                    return;
                }
            }
        }
        }

        if (this.prop1_count === 999) {
            this.acquire_prop1 = false;

            this.prop1_count = 998;
        }
        if (this.prop2_count === 999) {
            this.acquire_prop2 = false;

            this.prop2_count = 998;
        }
        if (this.prop3_count === 999) {
            this.acquire_prop3 = false;
            ;
            this.prop3_count = 998;
        }
        this.funcheckGameOver();
        // 更新玩家位置
        if (!this.player.isMovingRight) {
            this.player.y += this.player.speedY;
            if (this.player.y <= (this.height - (this.blocks[200].height * 7) + 10) || this.player.y + this.player.height >= this.height - (this.blocks[200].height * 2) - (this.player.height / 5)) {
                this.player.speedY = -this.player.speedY;
            }
        } else {
            this.player.x += 5;
            if (this.player.x >= this.width - this.blocks[0].width) //不能出手机边界
            {
                this.player.x = this.width * this.percentage;
                this.player.y = this.height - this.blocks[200].height * 3;
                this.player.isMovingRight = false;
            }
        }

        // 更新方块位置
        this.blocks.forEach(block => {
            block.x += block.speedX;
            block.y += block.speedY;
            block.speedY += 2;
        });

        // 检测方块碰撞
        this.blocks.forEach((block, index) => {
            this.blocks.forEach((otherBlock, otherIndex) => {
                if (index !== otherIndex && this.funcheckCollision(block, otherBlock)) {
                    if (block.speedY > 0 && block.y + block.height <= otherBlock.y + otherBlock.height) {
                        block.y = otherBlock.y - block.height;
                        block.speedY = 0;
                    }
                }
            });

            if (block.y + block.height > this.height) {
                block.y = this.height - block.height;
                block.speedY = 0;
            }
        });

        // 检测玩家与方块的碰撞
        let collidedBlocks = [];
        this.blocks.forEach(block => {
            if (this.funcheckCollision(this.player, block)) {
                collidedBlocks.push(block);
            }
        });

        if (collidedBlocks.length > 0) {
            this.funhandleCollision(collidedBlocks);
        }
        this.drawFrameContent();
        requestAnimationFrame(this.drawAnimate.bind(this));
    }

    // 绘制帧内容
    drawFrameContent() {
        this.context.clearRect(0, 0, this.width, this.height);
        this.context.drawImage(this.background, 0, 0, this.width, this.height);
        // this.context.drawImage(this.pause_icon, 20, 30, this.iconSize, this.iconSize);
        // this.context.drawImage(this.prop1_icon, this.prop1.x, this.prop1.y, this.prop1.width, this.prop1.height);
        if (this.prop1_count === 1) {
            this.context.fillStyle = 'pink';
            this.context.font = `bold ${this.size_1}px Arial`;
            this.context.textAlign = 'center';
            this.context.fillText('1', this.prop1.x + this.prop1.width, this.prop1.y + this.prop1.height / 4);
        }
        if (this.prop1_count === 998) {
            this.context.fillStyle = 'pink';
            this.context.font = `bold ${this.size_1}px Arial`;
            this.context.textAlign = 'center';
            this.context.fillText('0', this.prop1.x + this.prop1.width, this.prop1.y + this.prop1.height / 4);
        }
        // this.context.drawImage(this.prop2_icon, this.prop2.x, this.prop2.y, this.prop2.width, this.prop2.height);
        if (this.prop2_count === 1) {
            this.context.fillStyle = 'pink';
            this.context.font = `bold ${this.size_1}px Arial`;
            this.context.textAlign = 'center';
            this.context.fillText('1', this.prop2.x + this.prop2.width, this.prop2.y + this.prop2.height / 4);
        }
        if (this.prop2_count === 998) {
            this.context.fillStyle = 'pink';
            this.context.font = `bold ${this.size_1}px Arial`;
            this.context.textAlign = 'center';
            this.context.fillText('0', this.prop2.x + this.prop2.width, this.prop2.y + this.prop2.height / 4);
        }
        // this.context.drawImage(this.prop3_icon, this.prop3.x, this.prop3.y, this.prop3.width, this.prop3.height);
        if (this.prop3_count === 1) {
            this.context.fillStyle = 'pink';
            this.context.font = `bold ${this.size_1}px Arial`;
            this.context.textAlign = 'center';
            this.context.fillText('1', this.prop3.x + this.prop3.width, this.prop3.y + this.prop3.height / 3);
        }
        if (this.prop3_count === 998) {
            this.context.fillStyle = 'pink';
            this.context.font = `bold ${this.size_1}px Arial`;
            this.context.textAlign = 'center';
            this.context.fillText('0', this.prop3.x + this.prop3.width, this.prop3.y + this.prop3.height / 3);
        }
        this.context.drawImage(this.time_icon, 90, 30, this.iconSize, this.iconSize);
        this.context.drawImage(this.pig, this.player.x, this.player.y, this.player.width, this.player.height);
        if (this.bubbleTime <= 3) {
            this.bubble.drawBubble("哎哟~", this.player.x + this.player.width, this.player.y, this.maxBubbleSize);
        }

        if (this.onlyone) {
            this.imageNum = Math.floor(Math.random() * 3);
            this.onlyone = false;
        }
        if (this.bubble1Time <= 2) {
            this.reverseBubble.drawBubble("小样儿~", this.width / 2, this.height / 2, this.maxBubbleSize);
            // if (this.imageNum === 0) {
            //     this.reverseBubble.drawBubble("小样儿~", this.width / 2, this.height / 2, this.maxBubbleSize);
            //     // this.context.drawImage(this.treebubble1, this.width / 3 - 10, this.height / 4, this.player.width * 3, this.player.height * 3);
            // } else if (this.imageNum === 1) {
            //     this.reverseBubble.drawBubble("小样儿~", this.width / 2, this.height / 2, this.maxBubbleSize);
            //     // this.context.drawImage(this.treebubble2, this.width / 3 - 10, this.height / 4, this.player.width * 3, this.player.height * 3);
            // } else {
            //     this.reverseBubble.drawBubble("小样儿~", this.width / 2, this.height / 2, this.maxBubbleSize);
            //     // this.context.drawImage(this.treebubble3, this.width / 3 - 10, this.height / 4, this.player.width * 3, this.player.height * 3);
            // }
        }
        this.context.fillStyle = 'black';
        this.context.font = `${this.size_1}px Arial`;
        this.context.textAlign = 'center';
        this.context.fillText(`${this.countdownTime}s`, this.iconSize * 5 / 2, this.iconSize * 2);
        this.blocks.forEach((block, index) => {
            const blockTop = block.y;
            const blockBottom = block.y + block.height;
            const blockLeft = block.x;
            const blockRight = block.x + block.width;
            if (blockBottom <= this.visibleRect.top && blockTop >= -block.height * 2 && blockRight >= this.visibleRect.left && blockLeft <= this.visibleRect.right) {
              if(this.score>=this.height/block.height&&this.score<this.height/block.height+20){
                block.status = (block.random<=6) ? 'wood':'iron';
                block.cube = (block.random<=6) ? this.wood:this.iron;
              } else if(this.score >= this.height / block.height + 20 && this.score <= 100 - this.height / block.height){
                block.status = (block.random<4) ? 'wood'
                  :(block.random>=8) ? 'gold'
                  :'iron';
                block.cube = (block.random<4) ? this.wood
                  :(block.random>=8) ? this.gold
                  :this.iron;
              } else if(this.score>100 - this.height / block.height){
                block.status = (block.random<2) ? 'wood'
                  :(block.random>=5) ? 'gold'
                  :'iron';
                block.cube = (block.random<2) ? this.wood
                  :(block.random>=5) ? this.gold
                  :this.iron;
              }
            }
            // 只有当矩形部分或全部可见时才进行绘制
            if (blockBottom >= this.visibleRect.top && blockTop <= this.visibleRect.bottom &&
                blockRight >= this.visibleRect.left && blockLeft <= this.visibleRect.right) {
                // 在可见范围内，进行绘制操作
                if (block.status == 'floor') {
                    this.context.fillStyle = 'rgba(255,0,0,0)';
                } else {
                    this.drawBlock(block);
                }
            }
        });
        this.drawSegmentedRoundedRect(this.context, this.width / 100 * 5, this.height / 4, 10, this.height / 2, 20, this.energy);
        if (this.energy === 10) {
            this.context.fillStyle = 'black';
            this.context.font = '900 9px Arial'
            this.context.fillText('x', this.width / 100 * 5 + 4, this.height / 2 + 10);
            this.context.fillText('a', this.width / 100 * 5 + 4.5, this.height / 2);
            this.context.fillText('m', this.width / 100 * 5 + 4, this.height / 2 - 10);
        } else {
            this.context.fillStyle = 'black';
            this.context.font = '800 8px Arial'
            this.context.fillText(`10`, this.width / 100 * 5 + 4.5, this.height / 2 + 10);
            this.context.fillText(`/`, this.width / 100 * 5 + 5, this.height / 2);
            this.context.fillText(`${this.energy}`, this.width / 100 * 5 + 5, this.height / 2 - 10);
        }
    }

    drawRoundedRect(context, x, y, width, height, radius, color, borderWidth, borderColor) {
        context.beginPath();
        radius = Math.min(radius, width / 2, height / 2);

        context.moveTo(x + radius, y);
        context.lineTo(x + width - radius, y);
        context.arcTo(x + width, y, x + width, y + height, radius);
        context.lineTo(x + width, y + height - radius);
        context.arcTo(x + width, y + height, x, y + height, radius);
        context.lineTo(x + radius, y + height);
        context.arcTo(x, y + height, x, y, radius);
        context.lineTo(x, y + radius);
        context.arcTo(x, y, x + width, y, radius);

        context.closePath();

        // 填充颜色
        context.fillStyle = color;
        context.fill();

        // 绘制边框
        context.lineWidth = borderWidth;
        context.strokeStyle = borderColor;
        context.stroke();
    }

    drawSegmentedRoundedRect(context, x, y, width, height, radius, energy) {
        // 绘制背景圆角矩形
        this.drawRoundedRect(context, x, y, width, height, radius, 'rgba(128,128,128,0)', 1, 'black');

        // 计算填充的部分宽度
        const filledHeight = (energy / 10) * height;

        // 清除填充部分的区域
        context.save();
        context.globalCompositeOperation = 'destination-out'; // 只清除绘制区域
        context.beginPath();
        context.moveTo(x + radius, y);
        context.lineTo(x + width - radius, y);
        context.arcTo(x + width, y, x + width, y + filledHeight, radius);
        context.lineTo(x + width, y + filledHeight - radius);
        context.arcTo(x + width, y + filledHeight, x, y + filledHeight, radius);
        context.lineTo(x + radius, y + filledHeight);
        context.arcTo(x, y + filledHeight, x, y, radius);
        context.lineTo(x, y + radius);
        context.arcTo(x, y, x + width, y, radius);
        context.closePath();
        context.fill(); // 清除指定区域
        context.restore();

        // 绘制完整的圆角矩形
        context.save();
        context.beginPath();
        context.translate(x, y); // 移动到矩形左上角

        if (energy < 10) {
            var color = 'rgba(0, 0, 255, 0.7)';
        } else {
            color = 'red';
        }
        // 绘制填充部分的圆角矩形
        if (energy > 0)
            this.drawRoundedRect(context, 0, 0, width, filledHeight, radius, color, 1, 'black');
        context.restore();
    }

    funcheckGameOver() {
        this.countNum = 0;
        this.blocks.forEach((block, index) => { //检查当前偏移方块数
            if (block.angle !== 0) {
                this.countNum += 1;
            }
            if (this.countNum > 2) {
                this.isUpdating = false
                this.gameOver = true
            }
        })
    }

    funcheckCollision(rect1, rect2) {
        return rect1.x < rect2.x + rect2.width &&
            rect1.x + rect1.width > rect2.x &&
            rect1.y <= rect2.y + rect2.height &&
            rect1.y + rect1.height >= rect2.y;
    }

    funhandleCollision(collidedBlocks) {
        if (collidedBlocks.length === 1) {
            let block = collidedBlocks[0];
            if (block.status == 'wood') {
                if (this.countNum === 0 || (this.countNum !== 0 && block.angle !== 0)) { //判断是否有其它存在
                    if (block.angle === 0 || (block.angle !== 0 && this.countNum === 1)) {
                        if (settings.FORCE_OPEN === true) {
                            playWoodHitMusic();
                        }
                        this.player.isMovingRight = false;
                        block.angle = 0;    //bug修复
                        block.speedX = 20;
                        this.score++;
                        if (this.energy < 10) {
                            this.energy++;
                        }
                        this.blocks.forEach(b => {
                            if (b.y < block.y) {
                                b.speedY = 2;
                            }
                        });
                    } else if (block.angle !== 0 && this.countNum === 2) {
                        this.player.isMovingRight = false;
                        block.angle = 0;
                    } else {
                        this.isUpdating = false
                        this.gameOver = true
                    }
                } else {
                    this.isUpdating = false
                    this.gameOver = true
                }
            } else if (block.status == 'iron') {
              if (settings.FORCE_OPEN === true) {
                playMetalHitMusic();
            }
                if (this.energy === 10) {
                    this.energy = 0;
                    this.player.isMovingRight = false;
                    block.speedX = 20;
                    this.score++;
                    this.blocks.forEach(b => {
                        if (b.y < block.y) {
                            b.speedY = 2;
                        }
                    });
                } else {
                    this.player.isMovingRight = false;
                    block.status = 'wood';
                    block.cube = this.wood;
                    this.bubbleTime = 0;
                }
            } else if (block.status == 'gold') {
              if (settings.FORCE_OPEN === true) {
                playMetalHitMusic();
            }
                if (this.energy === 10) {
                    this.energy = 0;
                    this.player.isMovingRight = false;
                    block.status = 'wood';
                    block.cube = this.wood;
                } else {
                    this.player.isMovingRight = false;
                    block.status = 'iron';
                    block.cube = this.iron;
                    this.bubbleTime = 0;
                }
            } else {
                this.player.isMovingRight = false;
            }
        } else if (collidedBlocks.length === 2) {
            const [block1, block2] = collidedBlocks;
            this.player.isMovingRight = false;

            if (block1.angle === 0 && block2.angle === 0) {
                if (this.energy === 10) {
                    this.energy = 0;
                    this.player.isMovingRight = false;
                    if (block1.status === 'wood') {
                        block1.speedX = 20;
                        this.score++;
                        this.blocks.forEach(b => {
                            if (b.y < block1.y) {
                                b.speedY = 2;
                            }
                        });
                    } else if (block1.status === 'iron') {
                        block1.status = 'wood';
                        block1.cube = this.wood;
                    } else if (block1.status === 'gold') {
                        block1.status = 'iron';
                        block1.cube = this.iron;
                    }
                    if (block2.status === 'wood') {
                        block2.speedX = 20;
                        this.score++;
                        this.blocks.forEach(b => {
                            if (b.y < block2.y) {
                                b.speedY = 2;
                            }
                        });
                    } else if (block2.status === 'iron') {
                        block2.status = 'wood';
                        block2.cube = this.wood;
                    } else if (block2.status === 'gold') {
                        block2.status = 'iron';
                        block2.cube = this.iron;
                    }
                } else if (block1.y < block2.y) {
                    block1.angle = -Math.PI / 24;
                    block2.angle = Math.PI / 24;
                    if (this.energy > 2) {
                        this.energy -= 2;
                    } else {
                        this.energy = 0;
                    }
                    this.onlyone = true;
                    this.bubble1Time = 0;
                } else {
                    block1.angle = Math.PI / 24;
                    block2.angle = -Math.PI / 24;
                    if (this.energy > 2) {
                        this.energy -= 2;
                    } else {
                        this.energy = 0;
                    }
                    this.onlyone = true;
                    this.bubble1Time = 0;
                }

            } else if (block1.angle !== 0 || block2.angle !== 0) {
                if (block1.angle !== 0 && block2.angle !== 0) {
                    this.isUpdating = false
                    this.gameOver = true
                } else {
                    block1.angle = 0;
                    block2.angle = 0;
                }
            }

            this.blocks.forEach(b => {
                if (b.y < block1.y || b.y < block2.y) {
                    b.angleOffset = Math.random() * 0.02 - 0.01;
                }
            });
            this.blocks.forEach(b => {
                if (b.y < block1.y || b.y < block2.y) {
                    b.speedY = 0;
                }
            });
        }

        this.blocks.forEach(b => b.hasCollided = false);
        this.player.x = this.width * this.percentage;
        const up = this.height - (this.blocks[199].height * 2) - this.player.height;
        const down = this.height - (this.blocks[199].height * 7) + this.player.height;
        this.player.y = Math.floor(Math.random() * (up - down - 20) + down + 10);
    }

    //失败弹窗显示
    funshowLosePopup() {
        this.updating = false; // 停止更新
        // 禁用触摸事件
        wx.offTouchStart();
        // 创建 Lose 类实例，并传入当前 Canvas 的上下文和尺寸，以及重新开始的回调函数
        let losePopup = new Lose(this.canvas, this.width, this.height, this.score, this.funrestartGame.bind(this), this.funrebackHome.bind(this));
        losePopup.drawPopup(); // 绘制并显示弹窗
    }

    //胜利弹窗显示
    funshowWinPopup() {
        this.updating = false; // 停止更新
        // 禁用触摸事件
        wx.offTouchStart();
        // 创建 Lose 类实例，并传入当前 Canvas 的上下文和尺寸，以及重新开始的回调函数
        let winPopup = new Win(this.canvas, this.width, this.height, this.timeString ,this.funrebackHome.bind(this));
        winPopup.drawPopup(); // 绘制并显示弹窗
    }

    //暂停弹窗显示
    funshowPausePopup() {
        this.updating = false; // 停止更新
        // 禁用触摸事件
        wx.offTouchStart();
        let pausePopup = new Pause(this.canvas, this.width, this.height, this.funrestartGame.bind(this), this.funcontinueRebackGame.bind(this), this.funrebackHome.bind(this));
        pausePopup.drawPopup();
    }

    //道具1弹窗显示
    funshowProp1Popup() {
        this.updating = false; // 停止更新
        // 禁用触摸事件
        wx.offTouchStart();
        let prop1Popup = new Downgrade(this.canvas, this.width, this.height, this.prop1_count, this.funprop1RebackGame.bind(this));
        prop1Popup.drawPopup();
    }

    //道具2弹窗显示
    funshowProp2Popup() {
        this.updating = false; // 停止更新
        // 禁用触摸事件
        wx.offTouchStart();
        let prop2Popup = new Cancel(this.canvas, this.width, this.height, this.prop2_count, this.funprop2RebackGame.bind(this));
        prop2Popup.drawPopup();
    }

    //道具3弹窗显示
    funshowProp3Popup() {
        this.updating = false; // 停止更新
        // 禁用触摸事件
        wx.offTouchStart();
        let prop3Popup = new Remove(this.canvas, this.width, this.height, this.prop3_count, this.funprop3RebackGame.bind(this));
        prop3Popup.drawPopup();
    }

    //重新开始游戏
    funrestartGame() {
        this.buttonDestroy();
        new Checkpoint(this.canvas);
    }

    funrebackHome() {
        clearInterval(this.timer); // 停止定时器
        wx.offTouchStart(); // 停止触摸事件监听器    //暂停资源方式卡死
        this.buttonDestroy();
        const Home = new DashBoard(this.canvas);
    }

    funcontinueRebackGame() {
        this.buttonShow();
        this.updating = true; // 恢复更新
        this.isPausing = false;
        this.init();
    }

    funprop1RebackGame(count) {
        this.prop1_count = count;
        this.updating = true; // 恢复更新
        this.use_prop1 = false;
        this.init()
    }

    funprop2RebackGame(count) {
        this.prop2_count = count;
        this.updating = true; // 恢复更新
        this.use_prop2 = false;
        this.init()
    }

    funprop3RebackGame(count) {
        this.prop3_count = count;
        this.updating = true; // 恢复
        this.use_prop3 = false;
        this.init()
    }

    //音效打击声
    audioPlay() {
        const innerAudioContext = wx.createInnerAudioContext();
        innerAudioContext.autoplay = true;
        innerAudioContext.src = '/audios/percussive.mp3'; // 音频资源地址 
        innerAudioContext.onPlay(() => {
            console.log("播放成功!");
        });
        innerAudioContext.onError((error) => {
            wx.showModal({
                title: "播放出错",
                content: `详细错误信息：${error.errMsg}`,
            });
            console.log("播放出错", error);
        });
    }

    buttonDestroy() {
      this.button.forEach(bt => {
          bt.destroy();
      });
      // this.button = null;
  }

      buttonHide() {
        this.button.forEach(bt => {
            bt.hideButton();
        });
        // this.button = null;
      }

      buttonShow() {
        this.button.forEach(bt => {
          bt.showButton();
      });
      // this.button = null;
      }
}
